package com.xwli.business.util;

import cn.hutool.core.util.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Random;

/**
 * @author xwli
 * @date: 2022/11/8 10:00
 * @desc
 * @since JDK 1.8
 */
public class RandomNumUtils {

    public static final String LETTERCHAR = "abcdefghijkllmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static final String NUMBERCHAR = "0123456789";


    /**
    * @description: 返回一个定长的随机纯字母字符串(只包含大小写字母)
    * @params: [length]
    * @return: java.lang.String
    * @author: xwli
    * @date: 2022/11/8 14:45
    */
    public static String generateMixString(int length) throws NoSuchAlgorithmException {
        StringBuffer sb = new StringBuffer();
        Random random = SecureRandom.getInstanceStrong();
        for (int i = 0; i < length; i++) {
            sb.append(LETTERCHAR.charAt(random.nextInt(LETTERCHAR.length())));
        }
        return sb.toString();
    }

    /**
    * @description: 返回一个定长的随机纯数字字符串
    * @params: [length]
    * @return: java.lang.String
    * @author: xwli
    * @date: 2022/11/8 14:43
    */
    public static String generateMixInteger(int length) throws NoSuchAlgorithmException {
        StringBuffer sb = new StringBuffer();
        Random random = SecureRandom.getInstanceStrong();
        for (int i = 0; i < length; i++) {
            sb.append(NUMBERCHAR.charAt(random.nextInt(NUMBERCHAR.length())));
        }
        return sb.toString();
    }

    /**
    * @description: 返回指定位数范围内,随机位数数字+随机位数字母组合
    * @params: [length]
    * @return: java.lang.String
    * @author: xwli
    * @date: 2022/11/8 15:04
    */
    public static String generateNumMixStr(Integer length) throws NoSuchAlgorithmException {
        int randomNum = RandomUtil.randomInt(1,length); //包含1,不包含length
        StringBuilder randomStringBuilder = new StringBuilder();
        randomStringBuilder.append(generateMixInteger(randomNum));
        randomStringBuilder.append(generateMixString(length-randomNum));
        return randomStringBuilder.toString();
    }

    /**
    * @description: 返回指定位数数字+指定位数字母组合
    * @params: [numLen, strLen]
    * @return: java.lang.String
    * @author: xwli
    * @date: 2022/11/8 15:03
    */
    public static String generateNumMixStr(Integer numLen,Integer strLen) throws NoSuchAlgorithmException {
        StringBuilder randomStringBuilder = new StringBuilder();
        randomStringBuilder.append(generateMixInteger(numLen));
        randomStringBuilder.append(generateMixString(strLen));
        return randomStringBuilder.toString();
    }

    public static String getOrderCode(String province) throws NoSuchAlgorithmException {
        String timestamp = DateFormatUtils.format(new Date(), "yyMMddHHmmss");
        return StringUtils.joinWith("-", province, timestamp,generateMixInteger(5));
    }

}

